import re
import time
import requests
import execjs


class RoomInfoFetcher:
    def __init__(self):
        '''
        初始化 RoomInfoFetcher 类的实例。

        设置了最大尝试次数为 3，重试延迟时间为 5 秒，并加载了用于生成签名的 JavaScript 文件。
        '''
        self.max_attempts = 3
        self.retry_delay = 5  # 重试延迟时间（秒）
        self.js = execjs.compile(open("douyin.js", encoding="utf-8").read())

    def fetch_live_room_info(self, web_url):
        '''
        通过传入的 url 获取房间信息，包括 room_id、wss_url、ttwid

        参数:
            web_url (str): 抖音直播间的网页 URL

        返回:
            tuple: 包含房间 ID、WebSockets URL 和 TTWID 的元组，如果获取失败则返回 None
        '''
        attempt = 0
        while attempt < self.max_attempts:
            # 示例：从代理池中获取一个代理
            # proxy = proxy_pool.get_proxy()
            # proxy = '182.106.136.217:41044'
            try:
                requests.adapters.DEFAULT_RETRIES = 5 # 增加重连次数
                s = requests.session()
                s.keep_alive = False # 关闭多余连接
                res = s.get(
                    url=web_url,
                    headers={
                        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                    },
                    cookies={
                        "__ac_nonce": "0673ec9a500de7760d57b"
                    },
                    # proxies={"http": proxy, "https": proxy}
                )
            except requests.exceptions.ProxyError as e:
                if '454' in str(e):
                    # print(f"代理 {proxy}已过期 报错：{e} 尝试切换")
                    # proxy_pool.remove_proxy(proxy)
                    continue 
                else:
                    print(f"其他代理错误: {e}")
            except requests.exceptions.SSLError as e:
                print(f'{web_url} 触发ssl错误 重试')
                continue
            match_list = re.findall(r'"roomId\\":\\"(\d+)\\",', res.text)
            if match_list:
                room_id = match_list[0]
                # print(f'获取 {web_url} room_id {room_id} 成功')
                signature = self.get_signature(room_id)
                wss_url = self.generate_wss_url(room_id, signature)
                ttwid = res.cookies.get_dict()['ttwid']
                return [wss_url, ttwid, web_url]
            else:
                attempt += 1
                print(f'获取 {web_url} room_id 失败，第 {attempt} 次重试')
                time.sleep(3)
                continue
            
        print(f'获取 {web_url} room_id 失败，已达到最大重试次数')
        return None

    def get_signature(self, room_id):
        # 假设这里是获取签名的逻辑
        signature = self.js.call('get_signature', room_id)
        return signature

    def generate_wss_url(self, room_id, signature):
        # 假设这里是生成WebSockets URL的逻辑
        return f'wss://webcast5-ws-web-hl.douyin.com/webcast/im/push/v2/?app_name=douyin_web&version_code=180800&webcast_sdk_version=1.0.14-beta.0&update_version_code=1.0.14-beta.0&compress=gzip&device_platform=web&cookie_enabled=true&screen_width=1707&screen_height=960&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_version=5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/129.0.0.0%20Safari/537.36&browser_online=true&tz_name=Asia/Shanghai&cursor=d-1_u-1_h-7454404892600095779_t-1735613973910_r-1&internal_ext=internal_src:dim|wss_push_room_id:{room_id}|wss_push_did:7442190789591549466|first_req_ms:1726664969175|fetch_time:1726664969296|seq:1|wss_info:0-1726664969296-0-0|wrds_v:7415969568708889208&host=https://live.douyin.com&aid=6383&live_id=1&did_rule=3&endpoint=live_pc&support_wrds=1&user_unique_id=7359170990646314547&im_path=/webcast/im/fetch/&identity=audience&need_persist_msg_count=15&insert_task_id=&live_reason=&room_id={room_id}&heartbeatDuration=0&signature={signature}'
# # 示例用法
# fetcher = RoomInfoFetcher()
# response = fetcher.fetch_live_room_info('https://live.douyin.com/80017709309')
# if response:
#     room_id, wss_url, ttwid = response
#     print(f'Room ID: {room_id}')
#     print(f'WSS URL: {wss_url}')
#     print(f'TTWID: {ttwid}')
